import React, { useEffect, useRef, useState } from 'react';
import VideoControl from '@jd/jd-bsplayer';
import { FullscreenOutlined } from '@ant-design/icons';
import setting from './setting';
import styled from './index.less';
import CustomModal from './components/CustomModal';
import EyesTreeSelect from './components/EyesTreeSelect';
import { getSubjectChannels, getPlayingDetails } from './service';

let timer = null;

function EyesDemo({ height, width, config, editable, data }) {
  if (!data) return null;
  const { describeConfig, cycleConfig, videoConfig, zoomConfig } = config;
  const { describeShow } = describeConfig;
  const { turnOnCycle, gapTime } = cycleConfig;
  const { maxPlay, eyesConfig } = videoConfig;
  const { turnOnZoom, previewZoom } = zoomConfig;
  const [videoData, setVideoData] = useState([]);
  const [showModal, setShowModal] = useState(false);
  const [detailUrl, setDetailUrl] = useState('');
  const [originData, setOriginData] = useState([]);
  const curentPage = useRef();
  const resetId = useRef();

  // 组装描述样式
  const describeStyle = () => {
    let resultStyle = {};
    if (describeShow) {
      const { textAlign, describeFont, describeHeight, describeBorder, borderColor, bgColor } = describeConfig;
      resultStyle = describeFont;
      resultStyle.textAlign = textAlign;
      resultStyle.height = `${describeHeight}px`;
      resultStyle.lineHeight = `${describeHeight - 10}px`;
      resultStyle.border = `${describeBorder}px solid ${borderColor}`;
      resultStyle.backgroundColor = bgColor;
    }
    return resultStyle;
  };

  // 组装描述样式
  const detailsTextStyle = () => {
    const { describeFont } = describeConfig;
    const { fontFamily, fontSize, fontWeight } = describeFont;
    return {
      fontFamily,
      fontSize,
      fontWeight,
    };
  };

  // 根据渲染的视频对象，处理通道Url
  const handleUrl = async (renderData) => {
    if (eyesConfig && eyesConfig !== '-1') {
      const getUrlList = renderData.map((m) => m.id).filter((f) => f);
      if (getUrlList.length !== 0) {
        const playingDetails = await getPlayingDetails(getUrlList.join());
        if (playingDetails) {
          return renderData.map((m) => {
            m.url = playingDetails[m.id];
            return m;
          });
        }
      }
    }
    return renderData;
  };

  // 处理渲染数据
  const handleRenderData = async () => {
    const { current: thePage } = curentPage;
    if (thePage !== undefined) {
      const startCount = thePage * maxPlay;
      if (turnOnCycle) {
        const trunOnList = [];
        for (let i = 0; i < maxPlay; i++) {
          const setIndex = (i + startCount) % originData.length;
          const setValue = originData[setIndex] || { id: Math.floor(Math.random() * 1000000000) };
          if (i === maxPlay - 1) {
            resetId.current = setValue;
          }
          trunOnList.push(setValue);
        }
        setVideoData(await handleUrl(trunOnList));
      } else {
        setVideoData(await handleUrl(originData.slice(0, maxPlay)));
      }
    }
  };

  // 自动翻页
  const autoPagerChromeChange = () => {
    const { current: thePage } = curentPage;
    const { current: resetValue } = resetId;
    if (thePage !== undefined) {
      const startId = originData[originData.length - 1];
      if (startId) {
        if (resetValue && startId.id === resetValue.id && curentPage.current !== 0) {
          curentPage.current = 0;
        } else {
          ++curentPage.current;
        }
        handleRenderData();
      }
    }
  };

  // 动画设置
  const animationConfig = () => {
    if (turnOnCycle) {
      clearInterval(timer);
      timer = setInterval(autoPagerChromeChange, gapTime * 1000);
    } else {
      clearInterval(timer);
    }
  };

  // 打开详情窗口
  const openDetails = (url) => {
    clearInterval(timer);
    setDetailUrl(url);
    setShowModal(true);
  };

  // 关闭详情窗口
  const closeDetails = () => {
    animationConfig();
    setDetailUrl('');
    setShowModal(false);
  };

  // 处理初始显示的信息
  const handleInitInfo = () => {
    curentPage.current = 0;
    handleRenderData();
    animationConfig();
  };

  // 初始化数据
  useEffect(() => {
    if (eyesConfig && eyesConfig !== '-1') {
      getSubjectChannels(eyesConfig).then((subject) => {
        const setValue = subject.map((m) => ({
          id: m.channelId,
          title: m.channelName,
          url: '',
        }));
        setOriginData(setValue);
      });
    } else {
      setOriginData(data);
    }
  }, [data, eyesConfig]);

  // 修改播放路数初始数据
  useEffect(() => {
    handleInitInfo();
    return () => {
      clearInterval(timer);
    };
  }, [maxPlay, originData]);

  // 修改动画处理展示视频
  useEffect(() => {
    animationConfig();
    return () => {
      clearInterval(timer);
    };
  }, [turnOnCycle, gapTime]);

  // 在编辑页面预览遮罩层效果
  useEffect(() => {
    if (editable) {
      setDetailUrl('');
      if (previewZoom) {
        setShowModal(true);
      } else {
        setShowModal(false);
      }
    }
  }, [previewZoom]);

  // 渲染视频卡片
  const renderVideoCard = ({ id, title, url }) => (
    <div className={styled['video-wrapper']}>
      {describeShow && (
        <div className={styled['video-title']} style={describeStyle()} title={title}>
          {title}
        </div>
      )}
      <div className={styled['video-box']}>
        <VideoControl key={id} urls={[url]} showDefBg showToolBar={false}></VideoControl>
      </div>
      {turnOnZoom && (
        <div className={styled['video-details']}>
          <span onClick={() => openDetails(url)} style={detailsTextStyle()}>
            查看详情
            <FullscreenOutlined />
          </span>
        </div>
      )}
    </div>
  );

  return (
    <div style={{ height, width }} className={styled['eyes-box']} onMouseEnter={() => clearInterval(timer)} onMouseLeave={animationConfig}>
      {videoData.map((m) => renderVideoCard(m))}
      <CustomModal visible={showModal} url={detailUrl} onCancel={closeDetails} zoomConfig={zoomConfig} detailsTextStyle={detailsTextStyle()}></CustomModal>
    </div>
  );
}
EyesDemo.setting = setting;
EyesDemo.styleConfig = {
  eyesTreeSelect: (props) => <EyesTreeSelect {...props} />,
};

export default EyesDemo;
